# syntax=docker/dockerfile:1
FROM python:3.11-slim AS base

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

# 可配置的国内镜像（默认使用清华 TUNA）
ARG PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple
ARG PIP_TRUSTED_HOST=pypi.tuna.tsinghua.edu.cn
ARG APT_MIRROR=mirrors.tuna.tsinghua.edu.cn
ENV PIP_INDEX_URL=${PIP_INDEX_URL} \
    PIP_TRUSTED_HOST=${PIP_TRUSTED_HOST}

# 安装系统依赖
# 切换 apt 源并安装系统依赖（兼容新旧 Debian 版本）
RUN if [ -f /etc/apt/sources.list ]; then \
        sed -i "s|deb.debian.org|${APT_MIRROR}|g; s|security.debian.org|${APT_MIRROR}|g" /etc/apt/sources.list; \
    fi && \
    if [ -d /etc/apt/sources.list.d ]; then \
        find /etc/apt/sources.list.d -name "*.sources" -type f -exec sed -i "s|deb.debian.org|${APT_MIRROR}|g; s|security.debian.org|${APT_MIRROR}|g" {} + 2>/dev/null || true; \
        find /etc/apt/sources.list.d -name "*.list" -type f -exec sed -i "s|deb.debian.org|${APT_MIRROR}|g; s|security.debian.org|${APT_MIRROR}|g" {} + 2>/dev/null || true; \
    fi && \
    apt-get update && apt-get install -y --no-install-recommends \
        build-essential \
        libpq-dev && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 复制 requirements.txt 并安装依赖
COPY apps/backend/requirements.txt ./
# 配置 pip 使用国内镜像并安装依赖
RUN python -m pip config set global.index-url ${PIP_INDEX_URL} && \
    python -m pip config set global.trusted-host ${PIP_TRUSTED_HOST} && \
    pip install --no-cache-dir -r requirements.txt && \
    pip install --no-cache-dir gunicorn

# 复制项目根目录的 tools 文件夹
COPY tools ./tools

# 复制后端应用文件
COPY apps/backend .

ENV FLASK_HOST=0.0.0.0 \
    FLASK_PORT=5001

EXPOSE 5001

CMD ["gunicorn", "-w", "2", "-b", "0.0.0.0:5001", "app:app"]


